package org.efficientsoap.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;


import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

public class AsyncSOAPTask extends AsyncTask<Object, Integer, EfficientSoapDeserializer<?>> {

	private static final String TAG = AsyncSOAPTask.class
			.getSimpleName();
	private Context context;
	private OnAsyncSOAPTaskCompleted listener;
	// ProgressDialog dialog;
	private ProgressBar bar;
	private Boolean isvisibleOnlyOnProzess = false;
	private boolean resetProgressBarOnPostExecute = false;
	private EfficientSoapDeserializer<?> efficientSoapParser;
	private EfficientSoapSerializer<?> efficientSoapSerializer;
	private EfficientSoapHttpProxy sender;
	

	public AsyncSOAPTask(
			EfficientSoapSerializer<?> efficientSoapSerializer,
			EfficientSoapDeserializer<?> efficientSoapParser,EfficientSoapHttpProxy sender, Context context, ProgressBar pb) {
		
		this.efficientSoapSerializer = efficientSoapSerializer;
		this.efficientSoapParser = efficientSoapParser;
		this.context = context;
		this.listener=(OnAsyncSOAPTaskCompleted) context;
		this.bar = pb;
		this.sender = sender;

	}
	private AsyncSOAPTask(){	
	}
	
	public EfficientSoapDeserializer<?> getEfficientSoapParser() {
		return efficientSoapParser;
	}
	public void setIsvisibleOnlyOnProzess(Boolean isvisibleOnlyOnProzess) {
		this.isvisibleOnlyOnProzess = isvisibleOnlyOnProzess;
	}
	public void setResetProgressBarOnPostExecute(
			boolean resetProgressBarOnPostExecute) {
		this.resetProgressBarOnPostExecute = resetProgressBarOnPostExecute;
	}
	
	
	@Override
	protected void onPreExecute() {
		if(bar!=null && isvisibleOnlyOnProzess){
			bar.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected EfficientSoapDeserializer<?> doInBackground(Object... params) {

		BufferedReader br = null;

		long nts1 = 0;
		long nts2 = 0;

		// timestamp1 to measure serializing time in nanoseconds
		nts1 = System.nanoTime();
		// process request serializing
		StringWriter out = new StringWriter();
		BufferedWriter bw = new BufferedWriter(out);

		try {
			this.efficientSoapSerializer.process(bw);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// timestamp1 to measure serializing time in nanoseconds
		nts2 = System.nanoTime();
		// update UI
		publishProgress((int) ((1 / (float) 3) * 100));

		sender.setOutputWriter(out);
		try {
			br = sender.send();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// open response file
		// try {
		// br = new BufferedReader(new InputStreamReader(getAssets().open(
		// "generateComplexDataResponse.xml")), 8192);
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		// update UI
		publishProgress((int) ((2 / (float) 3) * 100));

		// timestamp1 to measure parsing time in nanoseconds
		long ntp1 = System.nanoTime();
		// process response parsing
		try {
			efficientSoapParser.process(br);
			this.efficientSoapParser = efficientSoapParser;
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (EfficientSoapFaultException e) {
			// TODO react to a possible SOAP fault here
			e.printStackTrace();
		}
		// timestamp2 to measure parsing time in nanoseconds
		long ntp2 = System.nanoTime();

		// update UI
		publishProgress((int) ((3 / (float) 3) * 100));

		// Log.v(TAG, out.toString());
		Log.v(TAG, "serializing took " + (nts2 - nts1) / 1000000 + "ms.");

		Log.v(TAG, "parsing took " + (ntp2 - ntp1) / 1000000 + "ms.");
		// Log.d(TAG, "Parsing took " + (t2 - t1) + "ms.");

		/*
		 * // updateProgress Dialog and dismiss the Dialog when it's done
		 * for (int i = 0; i < 50; i++) { //publishProgress(2); try {
		 * Thread.sleep(50); // wait 100ms } catch (InterruptedException e)
		 * { e.printStackTrace(); } }
		 */
		// setProgressBarVisibility(false);
		// dialog.dismiss();

		return efficientSoapParser;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		// Increment Progress Dialog with the Update
		// from the doInBackgroundMethod
		// dialog.incrementProgressBy(values[0]);
		if(bar!=null){
			bar.setProgress(values[0]);
		}
		
	}

	@Override
	protected void onPostExecute(EfficientSoapDeserializer<?> result) {
		if (!((Activity) context).isFinishing()) {
			// result="READY";
			
			if(bar!=null){
				if(isvisibleOnlyOnProzess){
					bar.setVisibility(View.INVISIBLE);
				}
				if(resetProgressBarOnPostExecute){
					bar.setProgress(0);
				}	
			}
			//listener.onAsyncSOAPTaskCompleted();
		}
		super.onPostExecute(result);
		
	}

}
